package com.advert.service.xml;

import com.advert.exception.ApplicationBusinessException;
import com.advert.exception.ApplicationRuntimeException;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.InputStream;

@Name("XmlBindingService")
@Scope(ScopeType.EVENT)
@AutoCreate
public class XmlBindingService {
    @Logger
    private Log logger;


    @SuppressWarnings("unchecked")
    public <T> T unmarshal(Class<T> clazz, File file) {
        T retVal = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            retVal = (T)jaxbContext.createUnmarshaller().unmarshal(file);
        } catch (JAXBException e) {
            logger.error("Error during unmarshalling from file {0}", e, file.getName());
            throw new ApplicationRuntimeException("Error during unmarshalling from file.", e);
        }
        return retVal;
    }

    @SuppressWarnings("unchecked")
    public <T> T unmarshal(Class<T> clazz, InputStream inputStream) {
        T retVal = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            retVal = (T)jaxbContext.createUnmarshaller().unmarshal(inputStream);
        } catch (JAXBException e) {
            logger.error("Error during unmarshalling from input stream.", e);
            throw new ApplicationRuntimeException("Error during unmarshalling from input stream.", e);
        }
        return retVal;
    }
}
